import json

import requests


# Tools definition for MCP Server
TOOLS = [
    {
        "type": "function",
        "name": "calculator",  # 必须是合法的函数名称
        "description": "Perform mathematical operations like addition, subtraction, multiplication, division.",
        "parameters": {
            "type": "object",  # 使用 JSON Schema 描述参数
            "properties": {
                "parameter1": {
                    "type": "number",
                    "description": "First number in the operation"
                },
                "parameter2": {
                    "type": "number",
                    "description": "Second number in the operation"
                },
                "operator": {
                    "type": "string",
                    "description": "The operation to perform: 'addition', 'subtraction', 'multiplication', 'division'"
                }
            },
            "required": ["parameter1", "parameter2", "operator"]  # 定义必需参数
        },
        "strict": True  # 限制模型严格遵守参数结构
    },
    {
        "type": "function",
        "name": "translator",  # 必须是合法的函数名称
        "description": "Translate text from one language to another.",
        "parameters": {
            "type": "object",  # 使用 JSON Schema 描述参数
            "properties": {
                "text": {
                    "type": "string",
                    "description": "Text to translate"
                },
                "from_language": {
                    "type": "string",
                    "description": "Source language code (e.g., 'en')"
                },
                "to_language": {
                    "type": "string",
                    "description": "Target language code (e.g., 'es')"
                }
            },
            "required": ["text", "from_language", "to_language"]  # 定义必需参数
        },
        "strict": True  # 限制模型严格遵守参数结构
    }
]

def calculator(parameter1, parameter2, operator):
    if operator == "addition":
        return parameter1 + parameter2
    elif operator == "subtraction":
        return parameter1 - parameter2
    elif operator == "multiplication":
        return parameter1 * parameter2
    elif operator == "division":
        if parameter2 != 0:
            return parameter1 / parameter2
        else:
            return "Error: Division by zero."
    else:
        return "Error: Invalid operator."

url = "https://api.siliconflow.cn/v1/chat/completions"

# MCP Server function
def mcp_server(user_input):
    # Step 1: Send user input and tools description to the model
    payload = {
        "model": "Qwen/QwQ-32B",
        "messages": [
            {
                "role": "user",
                "content": user_input
            }
        ],
        "tools": TOOLS  # 将工具列表传递到顶层的 tools 参数中
    }

    headers = {
        "Authorization": "Bearer sk-hbxoxotmmfsnsbcsvmeryrbjvfdqltpicciktjrjkspdhfxo",
        "Content-Type": "application/json"
    }

    print(json.dumps(payload, ensure_ascii=False))
    response = requests.post(url, json=payload, headers=headers)
    print(response)
    if response.status_code == 200:
        model_reply = response.json()

        # Step 2: Parse the model's response
        choices = model_reply.get("choices", [])
        if not choices:
            return "Error: No valid choices returned by the model."

        # Assuming the first choice contains the tool invocation details
        tool_invocation = choices[0].get("tool_invocation", {})
        tool_name = tool_invocation.get("tool_name")
        parameters = tool_invocation.get("parameters", {})

        # Step 3: Execute the tool (For simplicity, implementing for calculator)
        if tool_name == "calculator":
            result = calculator(
                parameter1=parameters.get("parameter1"),
                parameter2=parameters.get("parameter2"),
                operator=parameters.get("operator")
            )
            return result
        else:
            return f"Error: Tool {tool_name} not recognized or supported."
    else:
        return f"Error: Failed to call SiliconFlow API with status code {response.status_code}."

# Example of inputs MCP Client would send to MCP Server
user_input = "帮我计算21乘以97的值"
result = mcp_server(user_input)
print(result)